<?php

namespace Core\Common;

use App\Controller\Example\BaseExample;
use Core\Enums\ErrorEnum;
use Core\Result\Result;

class Common
{
    /**
     * sql对象赋值
     * @return object
     */
    public static function assemble($object,$data){
        foreach ($data as $item => $val){
            if(property_exists($object,$item)){
                $object->$item = $val;
            }
        }
        return $object;
    }
    //翻页通用
    public static function identical($data){
        $assemble = Common::assemble(new BaseExample(), $data);
        if($assemble->page ==null)$assemble->page=1;
        if($assemble->limit ==null)$assemble->limit=10;
        $assemble->pageStart =$assemble->limit*($assemble->page-1);
        return $assemble;
    }
    /**
     * curl请求
     * @return string
     */
    public function sendCurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 3);
        curl_setopt( $ch, CURLOPT_TIMEOUT , 8);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if ($params) {
            if (is_array($params)) {
                $paramsString = http_build_query($params);
            } else {
                $paramsString = $params;
            }
        } else {
            $paramsString = "";
        }
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $paramsString);
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($paramsString ){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$paramsString);
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }
    /** TODO 获取语言
     * 获取post参数
     * @return array|int
     */
    public static function getLanguage($language){
        if(empty($language)){
            return 0;
        }else{
            return $language-1;
        }
    }
    /**
     * 获取post参数
     * @return array
     */
    public static function getPost(){
        $response = json_decode(file_get_contents('php://input'), true);
        if(empty($response)){
            $response = $_REQUEST;
        }
        $data = [];
        foreach($response as $k=>$v)
        {
            if($k=="token"){
                $data[$k] =$v;
            }else{
                $data[$k] = Common::filter($v);
            }
        }
        return $data;
    }
    /**
     * 不登录验证
     * @return string
     */
    public static function noLogin($a,$token,$language){
        if (!in_array($a, self::api_nologin())) {
            if (!$token){
                exit(json_encode(array(
                    "code"=>401,
                    "msg"=>ErrorEnum::ACCOUNTINVALID[$language],
                    "data"=>null
                ),JSON_UNESCAPED_UNICODE));
            }
        }
    }
    /**
     * 判断不登录操作函数
     * @return array
     */
    public static function api_nologin(){
        return [
            'login', //登录
            'banner', //首页轮播图
            'languageList',//首页国籍
            'homeNotice',//首页公告
            'noticeList',//首页公告列表
            'register',//用户注册
            'forgotPassword',//忘记密码
            'sendCode',//发送验证码
            'goodsCategory',//商品分类
            'goodsList',//商品列表
            'goodsDetails',//商品详情
            'skuSearch',//sku筛选
            'AppUpdate',//app更新
            'crmBackendOrder',//
            'getTeam',//
            'getTeamDesc',//
            'winningInfo',
            'sach',
            'WeeklyDividends',//周分红
            'AutoSettCollectSaleReward',//自动结算(积分)
            'AutoSettCollectWinningReward',//自动结算(分享积分)
            'AutoSettCollectBonusReward',//自动结算(拓展积分)
        ];
    }
    /**
     * 参数过滤
     * @return string
     */
    private static function filter($data){
        /*$data=str_replace("#","",$data);
        $data=str_replace("<","",$data);
        $data=str_replace(">","",$data);
        //$data=str_replace("/","",$data);
        $data=str_replace("?","",$data);
        //$data=str_replace("@","",$data);//邮箱验证使用
        //$data=str_replace(":","",$data);
        $data=str_replace("$","",$data);
        $data=str_replace(";","",$data);
        //$data=str_replace(",","",$data);
        $data=str_replace("&","",$data);
        $data=str_replace("*","",$data);
        //$data=str_replace("'","",$data);
        $data=str_replace("+","",$data);
        //$data=str_replace("-","",$data);
        $data=str_replace("=","",$data);
        //$data=str_replace("\"","",$data);*/
       /* $data=str_replace(" ","",$data);	//英文的空格
        $data=str_replace(" ","",$data);	//中文的空格
        $data=str_replace(" ","",$data);	//中文的空格*/
        //注意，此处不能过滤"|"，因数据库中多个值用"|"做分隔符；
        /*$data = trim($data);
        $data = stripslashes($data);*/
        //$data = htmlspecialchars($data);
        //$过滤字符串 = ["#","<",">","?",";","&","*","'","=","$","\"","src","SRC","eval(","EVAL(","script","SCRIPT","select","update","insert","delete"];
        $过滤字符串 = ["$","src","SRC","eval(","EVAL(","script","SCRIPT","select","update","insert","delete"];
        foreach ($过滤字符串 as $v){
            if(count(explode($v,$data)) > 1)Result::error("非法参数 Illegal parameter");
        }
        return $data;
    }

    /**
     * 列表转树形 TODO
     * @param array $list 列表数组
     * @param string $pk 主键名称
     * @param string $pid 父键名称
     * @param integer $root 根节点id
     * @param string $child 子节点名称
     * @return array
     */
    public static function list_to_tree($list = [], $pk = 'id', $pid = 'pid', $root = 0, $child = 'children')
    {
        $tree = [];
        $refer = [];
        foreach ($list as $k => $v) {
            $refer[$v[$pk]] = &$list[$k];
        }
        foreach ($list as $key => $val) {
            $parent_id = 0;
            if (isset($val[$pid])) {
                $parent_id = $val[$pid];
            }
            if ($root == $parent_id) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parent_id])) {
                    $parent = &$refer[$parent_id];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
        return $tree;
    }

    /**
     * 文件链接 TODO
     * @param array $file 文件信息
     * @return string
     */
    public static function fileUrl($file)
    {
        $file_url = '';
        if ($file) {
            if ($file['storage'] == 'local') {
                $file_url = self::file_url($file['file_path']);
            } else {
                $file_url = $file['domain'] . '/' . $file['file_path'];
                if (strpos($file_url, 'http') !== 0) {
                    $file_url = 'http://' . $file_url;
                }
            }
        }
        return $file_url;
    }

    /**
     * TODO 文件地址
     * 协议/域名/文件路径
     *
     * @param string $file_path 文件路径
     *
     * @return string
     */
    private static function file_url($file_path = '')
    {
        if (empty($file_path)) {
            return '';
        }

        if (strpos($file_path, 'http') !== false) {
            return $file_path;
        }

        $server_url = 'http://'.$_SERVER['HTTP_HOST'];

        if (stripos($file_path, '/') === 0) {
            $res = $server_url . $file_path;
        } else {
            $res = $server_url . '/' . $file_path;
        }

        return $res;
    }
}